﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotnet.Entity;
using Hotnet.Dal.BaseRepository;
using Component.Utilities;
using Hotnet.Entity.Enum;
using Hotnet.Entity.Search;

namespace Hotnet.Dal.NSDalNews
{
	public class DalNewsList : Repository<NewsList>
	{
		public ViewNewsList[] List(SearchNewsList condition, int pageNo, int pageSize, out int totalCount)
		{
			int from = pageNo * pageSize + 1;
			int to = (pageNo + 1) * pageSize;
			totalCount = 0;

			string listTypeCondition = "";
			string orderByCondition = "";
			string newsNameCondition = "";
			string isPublishedCondition = "";
			string newsCategoryCondition = "";

			if (condition.ListType != null)
				listTypeCondition = string.Format(" and ListType={0} ", (int)condition.ListType);
			if (condition.OrderType == Hotnet.Entity.Enum.EnumOrder.添加时间 || condition.OrderType == null)
				orderByCondition = " NewsList.IsPublished,NewsList.AddTime ";
			else
				orderByCondition = " NewsList.IsPublished,ClickCount ";
			if (!string.IsNullOrEmpty(condition.NewsName))
				newsNameCondition = string.Format(" and Title like '%{0}%'", condition.NewsName);
			if (condition.NewsCategroyId != null)
				newsCategoryCondition = string.Format(" and CategoryID={0}", condition.NewsCategroyId);
			if (condition.IsPublished != null)
				isPublishedCondition = string.Format(" and NewsList.IsPublished={0} ", (int)condition.IsPublished);

			string strSql = string.Format(@"select * from (SELECT ROW_NUMBER() OVER (ORDER BY {5} desc)AS Row,
										 News.NewsID, News.Title, News.Summary, News.NewsTime, News.ImagePath, News.CategoryID, News.SourceFromID, 
										News.ClickCount, News.DefineType, News.IsPublished, NewsList.ListType, NewsList.CoverImageSrc, 
										NewsList.IsPublished AS NewsListIsPublished
										FROM [NewsList] join News on NewsList.NewsID=News.NewsID where 1=1 {0} {1} {2} {6} {7}) t1 WHERE Row between {3} and {4}", listTypeCondition, newsNameCondition, isPublishedCondition, from, to, orderByCondition, newsCategoryCondition, isPublishedCondition);
			string strCount = string.Format(@"SELECT count(*) 
										FROM [NewsList] join News on NewsList.NewsID=News.NewsID where 1=1 {0} {1} {2} {3} {4}", listTypeCondition, newsNameCondition, isPublishedCondition, newsCategoryCondition, isPublishedCondition);
			totalCount = disableCacheDataContext.ExecuteQuery<int>(strCount).FirstOrDefault();
			return disableCacheDataContext.ExecuteQuery<ViewNewsList>(strSql).ToArray();
		}
	}
}
